<template>
	<section>
		<!--工具条-->
		<el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
			<el-form :inline="true" >
				<el-form-item>
					<el-input v-model="keyword" placeholder="姓名" v-perm="'employee:list'"></el-input>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" v-on:click="keywordQuery" v-perm="'employee:getAll'">查询</el-button>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" @click="handleAdd" v-perm="'employee:updateAndSave'">新增</el-button>
				</el-form-item>
			</el-form>
		</el-col>

		<!--列表-->
		<el-table :data="employees" highlight-current-row v-loading="listLoading" @selection-change="selsChange"
              style="width: 100%;">
			<el-table-column type="selection" width="55" align="center">
			</el-table-column>
			<el-table-column type="index" width="60" align="center">
			</el-table-column>
			<el-table-column prop="username" label="员工姓名" width="110" sortable align="center">
			</el-table-column>
			<el-table-column prop="phone" label="电话" width="106" sortable align="center">
			</el-table-column>
			<el-table-column prop="email" label="邮箱" width="150" sortable align="center">
			</el-table-column>
<!--			<el-table-column prop="salt" label="暂定" width="100"  align="center">
			</el-table-column>-->
			<el-table-column prop="password" label="员工密码" width="150" sortable align="center">
			</el-table-column>
      <el-table-column prop="age" label="年龄" width="70"  align="center">
      </el-table-column>
      <el-table-column prop="state" label="状态" width="100" sortable align="center">
        <template scope="scope">
          <span style="color: #13ce66" v-if="scope.row.state==1">启用</span>
          <span style="color: red" v-else>禁用</span>
        </template>
      </el-table-column>
      <el-table-column prop="department.name" label="管理部门" width="80"  align="center">
      </el-table-column>
      <el-table-column prop="shop.name" label="门店" width="130"  align="center">
      </el-table-column>
      <el-table-column prop="role_name" label="角色身份" width="130"  align="center">
      </el-table-column>


			<el-table-column label="操作" width="180" align="center" >
				<template scope="scope">
					<el-button size="small" @click="handleSave(scope.$index, scope.row)" v-perm="'employee:updateAndSave'">编辑</el-button>
					<el-button type="danger" size="small" @click="handleDel(scope.$index, scope.row)" v-perm="'employee:delete'">删除</el-button>
				</template>
			</el-table-column>
		</el-table>

    <!--分页栏数据-->
    <el-col :span="24" class="toolbar">
      <el-button type="danger" @click="batchRemove" :disabled="this.sels.length===0" v-perm="'employee:patchDel'">批量删除</el-button>
      <el-pagination layout="prev, pager, next" @current-change="handleCurrentChange" :page-size="pageSize"
                     :total="totals" style="float:right;" :current-page="currentPage">
      </el-pagination>
    </el-col>


		<!--编辑界面-->
		<el-dialog :title="title" :visible.sync="saveFormVisible" :close-on-click-modal="false">
			<el-form :model="saveForm" label-width="80px" :rules="saveFormRules" ref="saveForm">
				<el-form-item label="员工姓名" prop="username">
					<el-input v-model="saveForm.username" auto-complete="off"></el-input>
				</el-form-item>
        <el-form-item label="员工密码" prop="password">
          <el-input v-model="saveForm.password" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="员工电话" prop="phone">
          <el-input v-model="saveForm.phone" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="员工邮箱" prop="email">
          <el-input v-model="saveForm.email"></el-input>
        </el-form-item>
        <el-form-item label="员工年龄" prop="age">
          <el-input v-model="saveForm.age"></el-input>
        </el-form-item>
        <el-form-item label="状态">
          <el-radio-group v-model="saveForm.state">
            <el-radio class="radio" :label="1">启用</el-radio>
            <el-radio class="radio" :label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="所属部门" prop="department_id">
          <el-cascader v-model="saveForm.department_id"
              :options="empTree"
              :props="{
                checkStrictly: true,
                label: 'name', // 级联框显示那个属性的值
                value: 'id'    // 回显时需要,回传值的时候也需要
              }"
              clearable></el-cascader>
        </el-form-item>

        <el-form-item label="所属角色">
          <el-select v-model="saveForm.role_id" placeholder="请选择">
            <el-option
                v-for="item in roles"
                :label="item.name"
                :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>



      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click.native="saveFormVisible = false">取消</el-button>
        <el-button type="primary" @click.native="saveSubmit" :loading="saveLoading">提交</el-button>
      </div>
		</el-dialog>
	</section>
</template>

<script>
	import util from '../../common/js/util'
	//import NProgress from 'nprogress'
	import { getUserListPage, removeUser, batchRemoveUser, editUser, addUser } from '../../api/api';

	export default {
		data() {
			return {
				employees: [],
				totals: 0,
        currentPage: 1,
        pageSize: 5,
        keyword : "",
        title :"",
				listLoading: false,
				sels: [],//列表选中列

        saveFormVisible: false,//编辑界面是否显示
        saveLoading: false,

        //表单匹配验证,name和sn必须输入值才能继续操作
        saveFormRules: {
          username: [
            {required: true, message: '请输入员工名字', trigger: 'blur'}
          ],
          password: [
            {required: true, message: '请输入员工密码', trigger: 'blur'}
          ],
          email: [
            {required: true, message: '请输入员工邮箱', trigger: 'blur'}
          ]
        },

        //编辑界面数据,都给默认值,重置数据方便添加方法,数值类型默认null,字符串默认空串
        saveForm: {
          id : null,
          username: '',
          phone: '',
          email: '',
          password : '',
          age : null,
          state: 1,
          department_id: null,
          logininfo_id: null,
          shop_id: null,
          role_id : null,
        },
        empTree :[],
        roles :[]
			}
		},


		methods: {
      getEmployees() {
        let para = {
          currentPage: this.currentPage,
          pageSize: this.pageSize,
          keyword: this.keyword
        };
        this.listLoading = true;
        this.$http.post("/employee",para).then(res =>{
          this.totals = res.data.totals;
          this.employees = res.data.data;
          //显示完毕将加载圈消失
          this.listLoading = false;
        }).catch(res =>{
          this.$message.error("网络繁忙,请稍后再试..")
        })
      },

			handleCurrentChange(val) {
				this.currentPage = val;
				this.getEmployees();
			},

      //3.高级查询
      keywordQuery(){
        this.currentPage = 1;
        this.getEmployees();
      },

      //4.单个删除
      handleDel: function (index, row) {
        //警告提示框
        this.$confirm('确认删除该记录吗?', '提示', {
          type: 'warning'
        }).then(() => { //点击确定进入then方法中
          this.listLoading = true;//开启加载圈
          //发送异步请求,将对象的id传给后端
          this.$http.delete("/employee/" + row.id).then(res => {
            if (res.data.success) {  //状态对象如果是true则删除成功进入if
              this.$message.success("删除成功!") //成功提示框
              //算出最后总页数
              var totalPage = Math.ceil(this.totals / this.pageSize);
              //如果当前页是总页数就是最后一页,并且个数模页数可以整除那就是每页最后一条,并且这不是第一页
              if (this.currentPage == totalPage && (this.totals - 1) % this.pageSize == 0 && this.currentPage != 1) {
                //满足条件就返回到删除页的前一页
                this.currentPage = this.currentPage - 1;
              }
              this.getEmployees();//删除完后调用列表数据展示
              this.listLoading = false;//关闭加载圈
            } else {
              //如果状态对象为false则失败,弹框提醒用户
              this.$message.error("网络繁忙~~请稍后再试..")
            }
          }).catch(() => {  //catch则是有异常 弹窗提醒
            this.$message.error("网络繁忙~~请稍后再试..")
          });
        }).catch(() => {
          //提示框点击取消则弹窗提醒
          this.$message.error("请重新操作..")
        });
      },

      selsChange: function (sels) {
        this.sels = sels;
      },
      //批量删除
      batchRemove: function () {
        var ids = this.sels.map(item => item.id)
        this.$confirm('确认删除选中记录吗？', '提示', {
          type: 'warning'
        }).then(() => {
          this.listLoading = true;
          //NProgress.start();
          this.$http.patch("/employee",ids).then(res =>{
            if(res.data.success) {
              this.$message.success("删除成功")
              this.currentPage = 1;
              this.getEmployees();
            }else {
              this.$message.error("网络繁忙...请稍后再试")
            }
          }).catch(res =>{
            this.$message.error("网络繁忙...请稍后再试")
          })
        }).catch(() => {

        });
      },

      //7.点击添加弹出对话框
      handleAdd: function () {
        this.title = "添加";  //动态修改标题
        this.saveForm = {   //每次点击将form表单中数据清空
          id : null,
          username: '',
          phone: '',
          email: '',
          password : '',
          age : null,
          state: 1,
          department_id: null,
          logininfo_id: null,
          shop_id: null,
          role_id : null,
          role_name: '',
        };
        this.saveFormVisible = true;  //显示添加对话框
        this.getEmpTree();
        this.getRoles();
      },

      //8.点击修改按钮弹出对话框
      handleSave: function (index, row) {
        //动态修改标题
        this.title = "修改";
        //回显数据
        //克隆对象防止列表中的数据也发生改变
        this.saveForm = Object.assign({}, row);//按照属性同名原则进行赋值
        //显示对话框
        this.saveFormVisible = true;
        this.getEmpTree();
        this.getRoles();
      },


      //9.添加或者修改对话框单击事件处理
      saveSubmit: function () {
        this.$refs.saveForm.validate((valid) => { //valid表单验证 满足条件则true
          if (valid) {
            //必填项都填了则弹窗确认提交框
            this.$confirm('确认提交吗？', '提示', {}).then(() => {
              this.saveLoading = true;
              //NProgress.start(); 对象克隆,防止model改变原数据
              let para = Object.assign({}, this.saveForm);

              if(para.department_id == null || para.department_id.length==0){
                para.department_id = null;
              }else if(para.department_id.length!=null){
                //有值就将父ID给parentId
                para.department_id = para.department_id[para.department_id.length-1]
              }
              //发送请求将克隆对象传入给后端
              this.$http.put("/employee",para).then(res =>{
                this.saveLoading = false; //关闭提交的加载框
                this.saveFormVisible = false; //关闭对话框
                if (res.data.success){  //状态对象 操作成功则进入if
                  this.$message.success("操作成功!");//弹窗提醒
                  this.getEmployees();//添加完成后关闭加载框、对话框并展示列表数据
                }else {
                  this.$message.error("系统繁忙,请稍后再试！")//状态对象false 弹窗提醒
                }
              }).catch(res =>{
                //代码错误,弹框提醒
                this.$message.error("系统繁忙,请稍后再试！")
              })
            });
          }
        });
      },

      getEmpTree(){
        this.$http.get("/employee/deptTree").then(res =>{
          this.empTree=res.data;
        })
      },

      getRoles(){
        this.$http.get("/role").then(res =>{
          this.roles = res.data
        })
      }
		},

		mounted() {
			this.getEmployees();
		}
	}

</script>

<style scoped></style>